package com.hy;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:根据前序遍历构造二叉搜索树
 * User:Mr.Du
 * Date:2023/12/4
 * Time:09:37
 */
public class BstFromPreorder {

    // [8,5,1,7,10,12]
    public TreeNode bstFromPreorder(int[] preorder) {
        TreeNode root = null;
        for(int i = 0;i < preorder.length;i++){
            root = dfs(root, preorder[i]);
        }
        return root;
    }

    public TreeNode dfs(TreeNode root, int val){
        if(root==null){
            return new TreeNode(val);
        }else{
            if(val>root.val) root.right = dfs(root.right,val);
            if(val<root.val) root.left = dfs(root.left,val);
        }
        return root;
    }
}
